function[sys, x0, str, ts] = state_observer(t, x, u, flag)
switch flag
    case 0
        [sys, x0, str, ts] = mdlInitializeSizes;
    case 1
        sys = mdlDerivatives(t, x, u);
    case 3
        sys = mdlOutputs(t, x, u);
    case {2, 4, 9}
        sys = [];
    otherwise
        error(['Unhandled flag = ', num2str(flag)]);
end


function [sys, x0, str, ts] = mdlInitializeSizes
sizes = simsizes;
sizes.NumContStates     =   4;
sizes.NumDiscStates     =   0;
sizes.NumOutputs        =   4;
sizes.NumInputs         =   2;
sizes.DirFeedthrough    =   0;
sizes.NumSampleTimes    =   0;
sys = simsizes(sizes);
x0  = [0.0; 0.0; 0.0; 0.0];
str = [];
ts  = [];


function sys = mdlDerivatives(t, x, u)
F = u(1);
p = x(1);
dp = x(2);
theta = x(3);
dtheta = x(4);

m = 1;
M = 1;
l = 1;
g = 9.80665;

A = [0, 1, 0, 0;
    0, 0, m * g / M, 0;
    0,0, 0, 1;
    0, 0, (m + M) * g / (M * l), 0];
B = [0; 1 / M; 0; 1 / (M * l)];
C = [1, 0, 0, 0];
L = place(A', C', [-10, -20, -30, -40])';
dX = (A - L*C) * x + B * u(1) + L * u(2);
sys(1) = dX(1);
sys(2) = dX(2);
sys(3) = dX(3);
sys(4) = dX(4);


function sys = mdlOutputs(t, x, u)
sys(1) = x(1);
sys(2) = x(2);
sys(3) = x(3);
sys(4) = x(4);